<!--
/**
* Author: gqz
* Date: 2021-08-30 15:23
* Desc: ZmPickerDate
*/
-->
<template>
  <view :style="customStyle" :class="customClass" class="zm-picker-date">
    <view @click="handleClick" class="zm-picker-date__label" v-if="showLabel">
      <slot>
        <text class="zm-picker-date__value" v-if="value">{{ label }}</text>
        <text class="zm-picker-date__placeholder" v-if="!value">
          {{ placeholder }}
        </text>
      </slot>
    </view>

    <u-picker
      mode="time"
      v-model="visible"
      :params="params"
      :default-time="defaultVal"
      @confirm="confirm"
      :start-year="startYear"
      :confirm-color="mainColor"
      :end-year="endYear"
    ></u-picker>
  </view>
</template>

<script lang="ts">
  import styleMixins from '@/mixins/styleMixins'
  import { Mixins, Component, Prop } from 'vue-property-decorator'
  import dayjs from 'dayjs'
  @Component({
    name: 'ZmPickerDate'
  })
  export default class ZmPickerDate extends Mixins(styleMixins) {
    @Prop({ type: String, default: '' }) value!: string
    @Prop({ type: String, default: 'date' }) type!: 'time' | 'date' | 'month'
    @Prop({ type: String, default: '2021' }) startYear!: string
    @Prop({ type: String, default: '2080' }) endYear!: string
    @Prop({ type: String, default: '选择日期' }) placeholder!: string
    @Prop({ type: Boolean, default: true }) showLabel!: boolean
    @Prop(Boolean) disabled!: boolean
    visible = false

    get params() {
      const data = { year: true, month: true, day: true }
      if (this.type === 'time') {
        return { ...data, hour: true, minute: true, second: true }
      } else if (this.type === 'month') {
        return { year: true, month: true }
      }
      return data
    }

    get fmt() {
      const fmtMap = {
        time: 'YYYY-MM-DD HH:mm:ss',
        month: 'YYYY-MM'
      }
      return fmtMap[this.type] || 'YYYY-MM-DD'
    }

    get label() {
      return dayjs(this.value).format(this.fmt)
    }

    get defaultVal() {
      const val = this.value || undefined
      return dayjs(val).format(this.fmt)
    }

    handleClick() {
      if (this.disabled) {
        return
      }
      this.visible = true
    }

    confirm(data) {
      console.log(data)
      const d = `${data.year}-${data.month}-${data.day}`
      if (this.type === 'time') {
        this.$emit('input', `${d} ${data.hour}:${data.minute}:${data.second}`)
        return
      }
      if (this.type === 'month') {
        this.$emit('input', `${data.year}-${data.month}-01`)
        return
      }
      this.$emit('input', d)
      console.log(data)
    }
  }
</script>

<style lang="scss" scoped>
  .zm-picker-date {
    &__placeholder {
      color: #c7c7c7;
    }
  }
</style>
